<template>
  <div class="new-table-style">
    <section class="search-style-box">
      <el-form ref="searchFrom" label-width="125px" size="small" :model="searchParams">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公司">
              <el-select v-model="searchParams.partnerAId" clearable filterable>
                <el-option v-for="item in options.assetList" :key="item.shopCode" :label="item.shopNumber" :value="item.shopCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产简码">
              <el-select v-model="searchParams.chargeItemCodes" clearable filterable>
                <el-option v-for="item in options.assetList" :key="item.shopCode" :label="item.shopNumber" :value="item.shopCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费项">
              <el-select v-model="searchParams.bizTypeList" clearable filterable multiple>
                <el-option v-for="item in options.chargeList" :key="item.key" :label="item.value" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-select v-model="searchParams.partnerBId" clearable filterable>
                <el-option v-for="item in options.clientList" :key="item.primaryKey" :label="item.partnerName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品牌名称">
              <el-select v-model="searchParams.operateBrandList" clearable filterable multiple>
                <el-option v-for="item in options.brandList" :key="item.primaryKey" :label="item.catalogName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-select v-model="searchParams.likeContractCode" clearable filterable>
                <el-option v-for="item in options.contractList" :key="item.contractCode" :label="item.contractCode" :value="item.contractCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应缴费开始时间">
              <el-date-picker v-model="searchParams.gePaymentDeadline" type="date" value-format="timestamp" :picker-options="pickerOptionsStart" clearable placeholder="请选择"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应缴费结束时间">
              <el-date-picker v-model="searchParams.lePaymentDeadline" type="date" value-format="timestamp" :picker-options="pickerOptions" clearable placeholder="请选择"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入开始时间">
              <el-date-picker v-model="searchParams.geCreateTime" type="date" value-format="timestamp" :picker-options="pickerWriteOptionsStart" clearable placeholder="请选择"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入结束时间">
              <el-date-picker v-model="searchParams.leCreateTime" type="date" value-format="timestamp" :picker-options="pickerWriteOptions" clearable placeholder="请选择"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-button type="primary" size="mini" class="f-right" @click="getList('')">查询</el-button>
            <el-button type="primary" size="mini" class="f-right margin-right-10" @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </section>
    <el-table ref="multipleTable" :row-key="getRowKeys" class="new-table-style bold-scrollbar-table" :border="true" :data="tableData" align="center" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :reserve-selection="true" width="55"> </el-table-column>
      <el-table-column align="center" label="账单状态" width="130">
        <template slot-scope="scope">
          <span v-if="scope.row.paymentStatus == 4">已结清</span>
          <span v-else-if="scope.row.paymentStatus == 8">已作废</span>
          <span v-else :class="scope.row.isOverdue ? 'color-red' : ''">{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同" prop="contractDesc" width="200">
        <template slot-scope="scope">
          <el-link :underline="false" @click="goContractInfo(scope.row)">{{ scope.row.contractDesc }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="账单说明" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.customerName">{{ scope.row.customerName }}</span>
          <span v-if="scope.row.operateBrandName">、{{ scope.row.operateBrandName }}</span>
          <span><br />({{ scope.row.chargeItemCode }}：{{ scope.row.assetTypeName }})</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="费项名称" class-name="no-padding" prop="bizTypeName" min-width="120"></el-table-column>
      <el-table-column align="center" label="应缴费日期" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.paymentDeadline | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="账单周期" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.cycleStartTime | formatDateTime('YYYY-MM-DD') }}</span
          ><br />
          <span>至</span><br />
          <span>{{ scope.row.cycleEndTime | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应收金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.amountReceivable | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已收金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <el-tooltip placement="right">
            <span>{{ scope.row.amountReceived | moneyFilterNoUnit }}</span>
            <div slot="content">
              <div class="padding-bottom-10">已收金额：{{ scope.row.amountReceived | moneyFilterNoUnit }}</div>
              <span>收款日期：{{ scope.row.chargeTime | formatDateTime('YYYY-MM-DD') }}</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="未结金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.unPaymentAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应缴滞纳金" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.lateFeesReceivable | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已减免滞纳金" class-name="no-padding" min-width="140">
        <template slot-scope="scope">
          <el-tooltip placement="right">
            <span>{{ scope.row.lateFeesReduction | moneyFilterNoUnit }}</span>
            <div slot="content">
              <div class="padding-bottom-10">减免金额：{{ scope.row.lateFeesReduction | moneyFilterNoUnit }}</div>
              <div>申请时间：{{ scope.row.lateFeesReductionDate | formatDateTime('YYYY-MM-DD') }}</div>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已缴纳滞纳金" class-name="no-padding" min-width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.lateFeesReceived | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="未缴滞纳金" class-name="no-padding" min-width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.lateFeesUnpaid | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="不含税金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ (accSubtr(scope.row.amountExcludeTax, scope.row.taxAmount) || 0) | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="税率" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.taxRate | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="税额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.taxAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应收生效" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.receivableEffective == 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="公司名称" class-name="no-padding" min-width="120" prop="enterpriseName"></el-table-column>
      <el-table-column align="center" label="备注" class-name="no-padding" min-width="120" prop="billDesc"></el-table-column>
      <el-table-column align="center" label="费用单号" class-name="no-padding" min-width="120" prop="billCode"></el-table-column>
      <el-table-column align="center" label="是否作废" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.paymentStatus == 8 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="录入日期" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-if="total > 0" @change="pageChange" :total="total" paginationLayout="total, prev, pager, next" />

    <div class="absolute-box btn-box">
      <div class="btn-content">
        <el-button v-if="['1', '2', '3', '4', '5'].includes(activeTab)" type="primary" size="mini" @click="exportFn">Excel导出</el-button>
        <el-dropdown v-if="['1', '2', '3', '4'].includes(activeTab)" class="margin-left-right-10">
          <el-button type="primary" size="mini">Excel导入核销<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <span @click="uploadLoad">下载模板</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-upload :show-file-list="false" action accept="" :http-request="event => leadFile(event.file)"> Excel文件导入 </el-upload>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button v-if="['1', '3'].includes(activeTab)" type="primary" size="mini" @click="openDialog('gatheradjust')">收款核销</el-button>
        <el-dropdown v-if="['1'].includes(activeTab)" class="margin-left-right-10">
          <el-button type="primary" size="mini">生成付款单<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <span @click="sendPayment">发送付款单</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <span @click="downloadPayment">下载付款单</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown v-if="['1'].includes(activeTab)" class="margin-left-right-10">
          <el-button type="primary" size="mini">生成催款函<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <span @click="sendCallPayment">发送催款函</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <span @click="downloadCallPayment">下载催款函</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button v-if="['1', '2', '3', '4'].includes(activeTab)" type="primary" size="mini" @click="addBill">新增账单</el-button>
        <el-button v-if="['1', '2'].includes(activeTab)" type="primary" size="mini" @click="openDialog('latefee')">滞纳金减免申请</el-button>
        <el-button v-if="['1', '3'].includes(activeTab)" type="primary" size="mini" @click="cancellationBill">作废</el-button>
      </div>
    </div>

    <!-- 添加账单 -->
    <bill-info ref="bill" @confirmAddBill="getList('')" :options="options" :check-list="checkList"></bill-info>
    <!-- 账单退款 -->
    <bill-refund ref="billrefund" @confirmBillRefund="refresh" :options="options" :check-list="checkList"></bill-refund>
    <!-- 收款核销 -->
    <gather-adjust ref="gatheradjust" @confirmGatherAdjust="refresh" :options="options" :check-list="checkList"></gather-adjust>
    <!-- 滞纳金减免 -->
    <late-fee ref="latefee" :check-list="checkList" @confirmLateFee="refresh"></late-fee>
  </div>
</template>

<script>
  import { apiBillList, apiBillExport, apiDunningLetter, apiSendMail, apiPaymentDownload, apiPaymentSendMail, apiImportReceivable } from '../../../api/billManage';
  import { accSubtr } from '@/common/js/utils.js';
  import billInfo from './billInfo.vue';
  import billRefund from './billRefund.vue';
  import gatherAdjust from './gatherAdjust.vue';
  import lateFee from './lateFee.vue';
  import { requestTips, askDialog } from '@js/utils';

  export default {
    name: 'billTable',

    props: {
      activeTab: {
        type: String,
        default: '',
      },
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
      assetTypeList: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },

    data() {
      return {
        pickerOptions: {
          disabledDate: time => {
            if (this.searchParams.gePaymentDeadline) {
              return time.getTime() < this.searchParams.gePaymentDeadline;
            }
          },
        },
        pickerOptionsStart: {
          disabledDate: time => {
            if (this.searchParams.lePaymentDeadline) {
              return time.getTime() > this.searchParams.lePaymentDeadline;
            }
          },
        },
        pickerWriteOptions: {
          disabledDate: time => {
            if (this.searchParams.geCreateTime) {
              return time.getTime() < this.searchParams.geCreateTime;
            }
          },
        },
        pickerWriteOptionsStart: {
          disabledDate: time => {
            if (this.searchParams.leCreateTime) {
              return time.getTime() > this.searchParams.leCreateTime;
            }
          },
        },
        assetCodeList: [],
        customList: [],
        operateBrandList: [],
        searchParams: {},
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        statusList: ['', '未结清', '未缴费', '逾期', '已结清'],
        checkList: [],
        accSubtr: accSubtr,
        loading: null,
      };
    },

    methods: {
      init() {
        this.getList();
      },

      //添加账单
      addBill() {
        this.$refs.bill.init('add');
      },

      //账单详情
      editItem(row) {
        this.$refs.bill.init('edit', row.primaryKey);
      },

      //重置
      reset() {
        this.searchParams = {};
        this.getList('');
      },

      refresh() {
        this.checkList = [];
        this.$refs.multipleTable.clearSelection();
        this.getList('');
      },

      //账单列表 queryType 1-待结清 2-今年已结清 3-今年未出账 4-全部账单
      async getList(more) {
        let res = await apiBillList({
          currentPage: more ? this.currentPage : 1,
          pageSize: this.pageSize,
          queryType: this.activeTab,
          ...this.searchParams,
        });
        res.rows.forEach(item => {
          let nowTime = new Date().getTime();
          let payTime = new Date(item.paymentDeadline).getTime();
          let diffTime = nowTime - payTime;
          let diffDays = Math.floor(diffTime / (1000 * 3600 * 24));
          diffDays = Math.abs(diffDays);
          if (nowTime > payTime) {
            item.isOverdue = true;
            item.statusName = '逾期' + diffDays + '天';
          } else {
            item.statusName = '距离缴费日期' + diffDays + '天';
          }
        });
        this.tableData = res.rows || [];
        this.total = res.total || 0;
      },

      //复选框选择
      handleSelectionChange(list) {
        this.checkList = this.lodash.cloneDeep(list);
      },

      //table唯一key
      getRowKeys(row) {
        return row.primaryKey;
      },

      //各种弹框的初始化
      openDialog(refName) {
        if (!this.isEmptyCheckList()) return;

        //收款/核销 选择账单的金额大于0是收款弹框 小于0是退款弹框, 收款核销收款金额>=0才能提交, 退款收款金额<0才能提交
        if (refName == 'gatheradjust') {
          let customerKeysList = this.checkList.map(item => {
            return item.customerKeys;
          });
          let len = Array.from(new Set(customerKeysList)).length;
          if (len > 1) {
            this.$message.warning('请选择相同客户的账单！');
            return;
          }

          let allNum = this.checkList.reduce((prev, item) => {
            prev += item.amountReceivable;
            return prev;
          }, 0);
          let name = allNum > 0 ? 'gatheradjust' : 'billrefund';
          this.$refs[name].init();
        } else {
          this.$refs[refName].init();
        }
      },

      //发送付款单
      sendPayment() {
        if (!this.isEmptyCheckList()) return;
        askDialog('确认发送付款单？', async () => {
          let res = await apiPaymentSendMail({
            items: this.checkList,
          });
          requestTips(res, () => {});
        });
      },

      //下载付款单
      downloadPayment() {
        if (!this.isEmptyCheckList()) return;
        askDialog('确认下载付款单？', async () => {
          apiPaymentDownload({
            items: this.checkList,
          });
        });
      },

      //发送催款函
      sendCallPayment() {
        if (!this.isEmptyCheckList()) return;
        askDialog('确认发送催款函？', async () => {
          let res = await apiSendMail({
            items: this.checkList,
          });
          requestTips(res, () => {});
        });
      },

      //下载催款函
      downloadCallPayment() {
        if (!this.isEmptyCheckList()) return;
        askDialog('确认下载催款函？', async () => {
          apiDunningLetter({
            items: this.checkList,
          });
        });
      },

      //下载核销模板
      uploadLoad() {
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = '/static/enteringTemplate.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },

      //作废
      cancellationBill() {
        if (!this.isEmptyCheckList()) return;
        let billKeys = this.checkList.map(item => {
          return item.primaryKey;
        });
        askDialog('确认作废？', async () => {
          let res = await apiBillCancelBill({
            primaryKeys: billKeys,
          });
          requestTips(res, () => {
            this.getList();
          });
        });
      },

      //判断是否选择账单
      isEmptyCheckList() {
        if (this.checkList == 0) {
          this.$message.warning('请选择账单！');
          return false;
        }
        return true;
      },

      //分页
      pageChange(page) {
        this.currentPage = page.currentPage;
        this.getList('more');
      },

      //核销导入
      leadFile(file) {
        this.showLoading();
        apiImportReceivable(file)
          .then(res => {
            this.$message.success('上传成功');
            this.getList();
            this.loading && this.loading.close();
          })
          .catch(e => {
            this.loading && this.loading.close();
          });
      },

      //导出
      async exportFn() {
        let res = await apiBillExport({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          queryType: this.activeTab,
          ...this.searchParams,
        });
        if (res.success) {
          window.location.href = res.url;
        } else {
          this.$message.warning(res.message);
        }
      },

      //合同详情
      goContractInfo(row) {
        let param = {
          contractType: row.contractType,
          contractCode: row.contractCode,
          contractKey: row.contractKey,
          contractCategory: row.contractCategory,
          headerName: '合同管理',
          showApprove: 'no',
        };

        let pathName = '/businessAssets/ContractManage/info?';
        for (let i in param) {
          pathName += i + '=' + param[i] + '&';
        }
        window.open(pathName);
      },

      showLoading() {
        this.loading = this.$loading({
          lock: true,
          text: '加载中……',
          background: 'rgba(0, 0, 0, 0.7)',
        });
      },
    },

    components: { billInfo, gatherAdjust, billRefund, lateFee },
  };
</script>

<style lang="scss" scoped>
  .search-style-box {
    background: #fbfbfb;
    border-radius: 3px;
    padding: 20px 20px 0;
    margin-bottom: 20px;
  }

  .btn-box {
    right: 0;
    top: -45px;
    width: calc(100% - 500px);
    overflow-x: auto;
    .btn-content {
      min-width: max-content;
      text-align: right;
      .el-button {
        margin-bottom: 5px;
      }
    }
  }

  ::v-deep .no-padding {
    padding: 0 !important;

    .cell {
      padding: 0 !important;
    }
  }
  ::v-deep .has-gutter tr th {
    border-right: 1px solid #787878;
  }
</style>
